import util from "../../utils/util.js";
import {
  LoginModel
} from "../../models/login.js";
import {
  getTokenModel,
  sendCodeModel
} from "../../models/common.js";
import {
  phoneValidate
} from '../../models/validate.js'
const loginModel = new LoginModel()
Page({
  data: {
    send: "获取验证码",
    sendTime: true,
    phone: "",
    code: "",
    canIUse: wx.canIUse("button.open-type.getUserInfo"),
  },
  onLoad() {
    //判断是加载过数据
  },
  // 提交授权数据，验证后跳转
  bindGetUserInfo() {
    //授权后才可以进行提交
    loginModel.getUserInfo().then(res => {
      const parm = {
        headimgurl: res.userInfo.avatarUrl,
        username: res.userInfo.nickName,
        sex: res.userInfo.gender
      };
      //查找服务器是否存在
      getTokenModel().then(res => {
        if (res.data.username) {
          //服务器存在，直接走验证跳转
          return this.loginBtn()
        }
        // 服务器不存在，提交，走验证跳转
        loginModel.submitUserInfo(parm).then(res => {
          console.log(res)
          this.loginBtn()
        })
      })
    })
  },
  //更新手机号
  upDatePhone(e) {
    this.setData({
      phone: e.detail.value
    });
  },
  //更新验证码
  upDateCode(e) {
    this.setData({
      code: e.detail.value
    });
  },
  // 手机号码验证
  loginSend() {
    const state = phoneValidate(this.data.phone)
    if (state) {
      if (this.data.sendTime) {
        this._sendTime(false)
        this._codePromise();
      }
    }
  },
  //发送验证码
  _codePromise() {
    const phone=this.data.phone
    const template=util.codeTepmpale.login
    sendCodeModel(phone,template).then(res => {
      console.log(res);
      if (res.errorCode == 0) {
        this._codeTime();
      } else {
        util.showToast(res.msg);
        this._sendTime(true)
      }
    })
  },
  //验证码倒计时
  _codeTime() {
    let num = 60;
    setInterval(() => {
      num--;
      if (num > 0) {
        this.setData({
          send: "" + num + "s"
        });
      }
      if (num == 0) {
        this._sendTime(true)
        this.setData({
          send: "获取验证码"
        });
      }
    }, 1000);
  },
  //提交
  loginBtn() {
    if (this.data.code.length == 0) {
      return util.showToast("您尚未输入验证码");
    }
    loginModel.submitCode(this.data.phone, this.data.code,
      res => {
        console.log(res)
        if (res.errorCode == 0) {
          //成功后设置缓存，跳转页面
          wx.setStorageSync("user", true);
          wx.redirectTo({
            url: "../index/index"
          });
        } else {
          util.showToast(res.msg);
        }
      })
  },
  //更新发送状态
  _sendTime(state) {
    this.setData({
      sendTime: state
    })
  },
  // 分享
  onShareAppMessage() {

  }
});